<?php
namespace Admin\Controller;
use Common\Controller\AdminBaseController;
/**
 * 微信
 */
class WeiXinController extends AdminBaseController{

	public function params(){
		$map['type'] = 'wechat';
        $data = D('Config')->getData($map);
        $this->assign('httpHost',$_SERVER['HTTP_HOST']);
        $this->assign('data', $data);
		$this->display();
	}

    public function index(){
        $param = I('post.');
        $assign = D('Ad')->getAdminList($param);
        $list = D('AdPosition')->select();
        $this->assign('list', $list);
        $this->assign('assign',$assign);
    	$this->display();
    }

    // public function test(){
    //     Vendor('aliyun-php-sdk-core.Config', '' ,'.php');
    //     $iClientProfile = \DefaultProfile::getProfile("cn-hangzhou", "LTAIvDF6vasKZOXO", "gYqKK4mqDOpuslJYFU8F5dAx9XDRoD");
    //     $client = new \DefaultAcsClient($iClientProfile);
    //     $request = new \Domain\Request\V20160511\CheckDomainRequest();
    //     $subFix = array('com','cn','com.cn','net','org','cc');
    //     $str = "";
    //     $content = "abc";
    //     foreach ($subFix as $key => $value) {
    //         $domain = $content.'.'.$value;
    //         $str .= $domain.'  ';
    //         $request->setDomainName($domain);
    //         $response = $client->getAcsResponse($request);
    //         $str.= ($response->Avail==1?"<a color='green' href='http://".$domain."'>未注册</a> ":'已注册')."\n";
    //     }
    //     p($str);
    // }


    /**
     * 关键字连接列表
     */
    public function keyword(){
        $param = I('get.');
        $data = D('WxKeyword')->where($param)->select();
        $data=\Org\Nx\Data::tree($data,'keyword','id','pid');
        $this->assign('keyword', $keyword);
        $this->assign('data', $data);
        $this->assign('page', $data['page']);
        $this->display();
    }

    /**
     * 添加关键字
     */
    public function addkw(){
        if (IS_POST) {
            $data=I('post.');
            if (D('WxKeyword')->addData($data)) {
                $this->success('添加成功',U('Admin/WeiXin/keyword')); 
            }else{
                $this->error('添加失败');
            }
        }else{
            $kw = D('WxKeyword')->select();
            $kw=\Org\Nx\Data::tree($kw,'keyword','id','pid');
            $this->assign('kw',$kw);
            $this->display();
        }
        
    }

    /**
     * 修改关键字
     */
    public function editkw(){
        if (IS_POST) {
            $data = I('post.');
            $map['id'] = $data['id'];
            $dbData = D('WxKeyword')->getData($map);
            if($data['url']!=$dbData['url']){
                $data['media_id'] = "";
            }
            if(D('WxKeyword')->editData($map,$data) !== false){
                $this->success('修改成功',U('Admin/WeiXin/keyword'));
            }else{
                $this->error('修改失败');
            }
        }else{                                                                                                                                                                         
            $map['id'] = I('get.id',0);
            $data = D('WxKeyword')->getData($map);
            //是否为图文
            if($data['type']==6 && !empty($data['values'])){
                $Model = new \Think\Model();
                $vData = $Model->query("select id,title from __PREFIX__article where id in(".$data['values'].") order by FIND_IN_SET(id,'".$data['values']."')");
                $this->assign('vData', json_encode($vData,true));    
            }else{
                $this->assign('vData', json_encode(array(),true));    
                
            }
            $this->assign('data', $data);
            $kw = D('WxKeyword')->select();
            $kw=\Org\Nx\Data::tree($kw,'keyword','id','pid');
            $this->assign('kw',$kw);
            $this->display();
        }
    }

    public function editkwAjax(){
        $id = I('post.id');
        $type = I('post.type');
        $param = I('post.param');
        $result = D('WxKeyword')->where(array('id'=>$id))->setField($type, $param);
        if($result){
            exit(json_encode(array('code'=>true)));
        }else{
            exit(json_encode(array('code'=>false)));
        }
    }

    /**
     * 删除关键字
     */
    public function deletekw(){
        $map['id'] = I('get.id');
        $result=D('WxKeyword')->deleteData($map);
        if($result){
            $this->success('删除成功',U('Admin/WeiXin/keyword'));
        }else{
            $this->error('删除成功');
        }
    }


    /**
     * 微信目录编辑
     */
    public function menu(){
        if(IS_POST){
            $post_menu = $_POST['menu'];
            foreach($post_menu as $k=>$v){
                $v['token'] = $wechat['token'];
                $menu_list = M('wx_menu')->getField('id',true);
                if(in_array($k,$menu_list)){
                   //更新
                   M('wx_menu')->where(array('id'=>$k))->save($v);
                }else{
                   //插入
                   M('wx_menu')->where(array('id'=>$k))->add($v);
                }
            }
            $this->success('操作成功,进入发布步骤');
            exit;
        }
        //获取最大ID
        $max_id = M()->query("SHOW TABLE STATUS WHERE NAME = '__PREFIX__wx_menu'");
        $max_id = $max_id[0]['auto_increment'];

        //获取父级菜单
        $p_menus = M('wx_menu')->where(array('pid'=>0))->order('id ASC')->select();
        $p_menus = convert_arr_key($p_menus,'id');
        //获取二级菜单
        $c_menus = M('wx_menu')->where(array('pid'=>array('gt',0)))->order('id ASC')->select();
        $c_menus = convert_arr_key($c_menus,'id');
        $this->assign('p_lists',$p_menus);
        $this->assign('c_lists',$c_menus);
        $this->assign('max_id',$max_id ? $max_id-1 : 0);
        $this->display();
    }

    /*
     * 删除菜单
     */
    public function delMenu(){
        $id = I('get.id');
        if(!$id){
            exit('fail');
        }
        $row = M('wx_menu')->where(array('id'=>$id))->delete();
        $row && M('wx_menu')->where(array('pid'=>$id))->delete(); //删除子类
        if($row){
            exit('success');
        }else{
            exit('fail');
        }
    }

    /*
     * 生成微信菜单
     */
    public function publishMenu(){
        //获取菜单
        $wechat = M('wx_user')->find();
        //获取父级菜单
        $p_menus = M('wx_menu')->where(array('pid'=>0))->order('id ASC')->select();
        $p_menus = convert_arr_key($p_menus,'id');

        $post_str = $this->convert_menu($p_menus);
       
        // http post请求
        if(!count($p_menus) > 0){
           $this->error('没有菜单可发布');
            exit;
        }
        $wechat = getWechat();
        if($wechat->createMenu($post_str)){
            $this->success('菜单已成功生成');
        }else{
            $this->error($wechat->errMsg);
        }
    }

    //菜单转换
    private function convert_menu($p_menus){
        $key_map = array(
            'scancode_waitmsg'=>'rselfmenu_0_0',
            'scancode_push'=>'rselfmenu_0_1',
            'pic_sysphoto'=>'rselfmenu_1_0',
            'pic_photo_or_album'=>'rselfmenu_1_1',
            'pic_weixin'=>'rselfmenu_1_2',
            'location_select'=>'rselfmenu_2_0',
        );
        $new_arr = array();
        $count = 0;
        foreach($p_menus as $k => $v){
            $new_arr[$count]['name'] = $v['name'];

            //获取子菜单
            $c_menus = M('wx_menu')->where(array('pid'=>$k))->select();

            if($c_menus){
                foreach($c_menus as $kk=>$vv){
                    $add = array();
                    $add['name'] = $vv['name'];
                    $add['type'] = $vv['type'];
                    // click类型
                    if($add['type'] == 'click'){
                        $add['key'] = $vv['value'];
                    }elseif($add['type'] == 'view'){
                        $add['url'] = $vv['value'];
                    }else{
                        $add['key'] = $key_map[$add['type']];
                    }
                    $add['sub_button'] = array();
                    if($add['name']){
                        $new_arr[$count]['sub_button'][] = $add;
                    }
                }
            }else{
                $new_arr[$count]['type'] = $v['type'];
                // click类型
                if($new_arr[$count]['type'] == 'click'){
                    $new_arr[$count]['key'] = $v['value'];
                }elseif($new_arr[$count]['type'] == 'view'){
                    //跳转URL类型
                    $new_arr[$count]['url'] = $v['value'];
                }else{
                    //其他事件类型
                    $new_arr[$count]['key'] = $key_map[$v['type']];
                }
            }
            $count++;
        }
        return array('button'=>$new_arr);
    }
    
}
